﻿package com.badibadi.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import com.badibadi.activity.BaseActivity.OnMyDialogeClistener;
import com.badibadi.adapter.AreaAdapter;
import com.badibadi.infos.Results;
import com.badibadi.infos.UserInfoModel;
import com.badibadi.mytools.AreaDialog;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.IOUtils;
import com.badibadi.mytools.ImageTools;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MySharePreferences;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.TempTools;
import com.badibadi.mytools.UpdateImageThead;
import com.badibadi.mytools.UserDataSet;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.XUtils;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.R.layout;
import com.badibadi.uniclubber.R.menu;
import com.libjph.util.StringUtil;
//import com.lidroid.xutils.util.LogUtils;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * ApplyMaster暂时还要改
 * 
 * @author Administrator RL_UpData
 * 
 */
public class ExpertApplyForActivity extends BaseActivity implements
		OnClickListener {

	private RelativeLayout head_img;// RL_UpData

	private ImageView iv_image = null;

	private TextView Name;
	private TextView E_mail;
	private TextView Sex;
	private TextView PhoneNumber;
	private TextView From;
	private TextView UpData;

	private UserInfoModel userInfoModel;
	private UserDataSet userDataSet;
	private FinalBitmap finalBitmap;
	// 下面的是点击后修改资料
	private static final int MINGCHENG = 11;
	private static final int EMAIL = 22;
	private static final int SEX = 33;
	private static final int PHONEUMBER = 44;
	private static final int FROM = 55;
	// 用于从sdcard获取图片
	private static final int FILE_SELECT_CODE = 8081;

	private static final String MSG_PATH = "msg";

	private String id;
	private String ExpertType;// 达人种类
	private String dataInfo = "";// 申请资料
	private AreaDialog areaDialog;
	private AreaAdapter areaAdapter;
	private int languageType = 0;
	private MySharePreferences preferences;

	String fileName;// 上传的证明资料名称

	String fileUri;// 上传证明的网络路径

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(ExpertApplyForActivity.this);
				// Is_Area_Dialog(RegirstrationActivity.this);
				areaDialog.AreaDisplayDialog();
				areaAdapter = new AreaAdapter(ExpertApplyForActivity.this,
						areaDialog.areaModelscountry);
				areaDialog.holderView.area_country_name_spinner
						.setAdapter(areaAdapter);
				break;
			case 2:
				Utils.ExitPrgress(ExpertApplyForActivity.this);
				try {
					Utils.showMessage(ExpertApplyForActivity.this, "网络连接出错");
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 4:
				Utils.ExitPrgress(ExpertApplyForActivity.this);
				areaAdapter = new AreaAdapter(ExpertApplyForActivity.this,
						areaDialog.areaModelscity);
				areaDialog.holderView.area_city_name_spinner
						.setAdapter(areaAdapter);
				break;
			case 5:
				Utils.ExitPrgress(ExpertApplyForActivity.this);
				try {
					Utils.showMessage(ExpertApplyForActivity.this,
							getResources().getString(R.string.l_xb69));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 11:
				Utils.ExitPrgress(ExpertApplyForActivity.this);
				try {
					RefreshData();
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 3:
				Utils.ExitPrgress(ExpertApplyForActivity.this);
				areaAdapter = new AreaAdapter(ExpertApplyForActivity.this,
						areaDialog.areaModelssheng);
				areaDialog.holderView.area_province_name_spinner
						.setAdapter(areaAdapter);
				break;
			case 14:
				Utils.ExitPrgress(ExpertApplyForActivity.this);
				try {
					Utils.showMessage(ExpertApplyForActivity.this,
							getResources().getString(R.string.l_xb70));
					Constants.is_shuaxin = true;
					ExpertApplyForActivity.this.finish();
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 7:
				String[] display = msg
						.getData()
						.getString("来自",
								getResources().getString(R.string.l_x2))
						.split(" ");
				if (display != null && display.length > 0) {
					From.setText(display[1] + " " + display[2]);
					String area_id = display[3];
					userInfoModel.setArea_id(area_id);
					userDataSet.UserDataSet(userInfoModel, 0, "", true);

				} else {
					From.setText(getResources().getString(R.string.l_x2));
					// area_id = null;
				}

				break;
			case 15:// 上传达人证明资料成功
				Utils.ExitProgress_hen(ExpertApplyForActivity.this);
				try {
					// Utils.showMessage(ExpertApplyForActivity.this,
					// "资料提交成功");
					if (fileName != null) {
						UpData.setText("" + fileName);

					}
					fileUri = msg.getData().getString(MSG_PATH);

				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 16:// 上传达人证明资料失败
				// Utils.ExitPrgress(ExpertApplyForActivity.this);
				Utils.ExitProgress_hen(ExpertApplyForActivity.this);
				try {
					Utils.showMessage(ExpertApplyForActivity.this,
							getResources().getString(R.string.l_xb71));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 17:// 上传达人证明资料失败
//				Utils.ExitPrgress(ExpertApplyForActivity.this);
				try {
					// Utils.showMessage(ExpertApplyForActivity.this,
					// getResources().getString(R.string.l_xb71));
//					LogUtils.d(""+msg.getData().getInt("msg", 100));
					Utils.setProgress_hen(msg.getData().getInt("msg", 100));
				
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			default:
				break;
			}
		}
	};

	// private static final int UPDATA = 66;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		finalBitmap = FinalBitmap.create(ExpertApplyForActivity.this);
		finalBitmap.configLoadfailImage(R.drawable.aah);
		finalBitmap.configLoadingImage(R.drawable.aah);
		// 磁盘缓存路径
		finalBitmap.configDiskCachePath(IOUtils.getSaveObjectPath(this,
				"ExpertApplyForActivity"));
		finalBitmap.configDiskCacheSize(10 * 1024);
		setContentView(R.layout.expert_apply_for);
		id = Utils.getUid(ExpertApplyForActivity.this);
		ExpertType = getIntent().getStringExtra("GetDataId");
//		   
		init();
		// 上传达人资料

	}

	// 上传达人资料
	protected void upData(final String filePath) {
		// TODO Auto-generated method stub
		fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
		// Utils.showPrgress(this);
		Utils.showProgress_hen(ExpertApplyForActivity.this);
		Utils.setProgress_henMax(100);
		new Thread(new Runnable() {

			@Override
			public void run() {

				AjaxParams params = new AjaxParams();
				try {
					params.put("fileName", fileName);
					params.put("uid", Utils.getUid(ExpertApplyForActivity.this));
					params.put("info_head", new File(filePath));
				} catch (FileNotFoundException e1) {
//					   
					   
				}// "/storage/sdcard1/DCIM/Camera/IMG_20140723_231753.jpg")
					// <<<<<<< .mine
				// LogUtils.d("fileName="+fileName+"/filePath="+filePath);
				// =======
				//    
				// >>>>>>> .r367
				FinalHttp fh = new FinalHttp();
				fh.post(Constants.BadiUrl_1 + "/" + "user/uploadExpertFile",
						params, new AjaxCallBack<Object>() {

							@Override
							public void onLoading(long count, long current) {
								// TODO Auto-generated method stub
								super.onLoading(count, current);
//								LogUtils.i("count-->" + count + "current-->"
//										+ current);
								Message msg = new Message();
								msg.what=17;
								Bundle bun = new Bundle();
								bun.putInt("msg", (int) count);
								msg.setData(bun);
								// bun.putInt("msg", );
                                handler.sendMessage(msg);

							}

							@Override
							public void onSuccess(final Object t) {
								// TODO Auto-generated method stub

//								LogUtils.i("T-->" + t + "current-->"
//										+ t.toString());
								if (t != null) {
									Results results = Utils.checkResult_NNN(
											ExpertApplyForActivity.this,
											t.toString());
//									   
									if (results != null) {
										if (results.isRet() == true) {
											Message msg = new Message();
											msg.what = 15;
											Bundle bun = new Bundle();

											bun.putString("msg",
													results.getRetmsg());
											msg.setData(bun);
											handler.sendMessage(msg);
										} else {
											handler.sendEmptyMessage(16);
										}

										super.onSuccess(t);
									} else {
										handler.sendEmptyMessage(16);
									}
								} else {
									handler.sendEmptyMessage(16);
								}
							}

						});
			}
		}).start();
	}

	private void init() {
		// TODO Auto-generated method stub
		preferences = new MySharePreferences(getApplicationContext(),
				"language");
		languageType = preferences.get("language", 0);
		areaDialog = new AreaDialog(ExpertApplyForActivity.this, languageType,
				handler);
		this.findViewById(R.id.expert_apply_for_return).setOnClickListener(
				ExpertApplyForActivity.this);
		this.findViewById(R.id.expert_apply_for_head_img).setOnClickListener(
				this);
		this.findViewById(R.id.ExpertApply_btn).setOnClickListener(this);
		// 头像
		iv_image = (ImageView) this.findViewById(R.id.head_img);
		// 名称
		Name = (TextView) this.findViewById(R.id.Name);

		this.findViewById(R.id.RL_ming_cheng).setOnClickListener(this);
		// E_mail
		E_mail = (TextView) this.findViewById(R.id.E_mail);

		// this.findViewById(R.id.RL_E_mail).setOnClickListener(this);
		// Sex
		Sex = (TextView) this.findViewById(R.id.Sex);

		this.findViewById(R.id.RL_Sex).setOnClickListener(this);
		// PhoneNumber
		PhoneNumber = (TextView) this.findViewById(R.id.PhoneNumber);

		this.findViewById(R.id.RL_PhoneNumber).setOnClickListener(this);
		// From
		From = (TextView) this.findViewById(R.id.From);

		this.findViewById(R.id.RL_From).setOnClickListener(this);
		// 相关资料
		UpData = (TextView) this.findViewById(R.id.UpData);
		this.findViewById(R.id.RL_UpData).setOnClickListener(this);
		userDataSet = new UserDataSet(ExpertApplyForActivity.this);
		Utils.showPrgress(ExpertApplyForActivity.this);
		Thread t = new Thread(new RefreshDataThread(id));
		t.start();

	}

	/**
	 * 从网络下载数据
	 */
	private void GenxinData() {
		Thread t = new Thread(new RefreshDataThread(id));
		t.start();
	}

	/**
	 * 刷新和更新数据
	 */
	private void Refresh() {
		GenxinData();
		RefreshData();
	}

	public void setId(String id) {
		this.id = id;
	}

	/**
	 * 吧数据更新到界面上
	 */
	private void RefreshData() {
//		   
		if (userInfoModel != null) {
			if (!StringUtil.isNullOrEmpty(userInfoModel.getHead())) {
				finalBitmap.display(iv_image, Constants.BadiDownImgUrl
						+ userInfoModel.getHead() + Constants.appPhoto4img);
			}

			Name.setText(userInfoModel.getNickName());
			E_mail.setText(userInfoModel.getEmail());

			Sex.setText(TempTools.TempNumToSex(ExpertApplyForActivity.this,
					userInfoModel.getSex()));
			PhoneNumber.setText(userInfoModel.getPhone());
			From.setText(userInfoModel.getSavename() + " "
					+ userInfoModel.getCityname());
			// UpData
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.expert_apply_for_return:
			ExpertApplyForActivity.this.finish();
			break;
		case R.id.expert_apply_for_head_img:// 头像

			break;
		case R.id.RL_ming_cheng:
			Intent intent = new Intent(ExpertApplyForActivity.this,
					ModifyTheDataActivity.class);
			intent.putExtra("id", 1);
			intent.putExtra("KEY1", "" + userInfoModel.getNickName());
			intent.putExtra("userInfoModel", userInfoModel);
			startActivity(intent);
			// startActivityForResult(intent, MINGCHENG);
			finish();
			overridePendingTransition(R.anim.slide_left, R.anim.slide_right);
			break;
		case R.id.RL_E_mail:
			// Intent intent2 = new Intent(ExpertApplyForActivity.this,
			// ModifyTheDataActivity.class);
			// intent2.putExtra("id", 2);
			// intent2.putExtra("KEY2", "" + userInfoModel.getEmail());
			// intent2.putExtra("userInfoModel", userInfoModel);
			// startActivity(intent2);
			// // startActivityForResult(intent2, EMAIL);
			// finish();
			// overridePendingTransition(R.anim.slide_left, R.anim.slide_right);
			break;
		case R.id.RL_Sex:

			setSex();

			break;
		case R.id.RL_PhoneNumber:
			Intent intent4 = new Intent(ExpertApplyForActivity.this,
					ModifyTheDataActivity.class);
			intent4.putExtra("id", 4);
			intent4.putExtra("KEY4", "" + userInfoModel.getPhone());
			intent4.putExtra("userInfoModel", userInfoModel);
			startActivity(intent4);
			// startActivityForResult(intent4, PHONEUMBER);
			finish();
			overridePendingTransition(R.anim.slide_left, R.anim.slide_right);
			break;
		case R.id.RL_From:
			// Intent intent5=new
			// Intent(ExpertApplyForActivity.this,ModifyTheDataActivity.class);
			// intent5.putExtra("id", 5);
			// intent5.putExtra("KEY5", ""+From.getText().toString().trim());
			// startActivityForResult(intent5, FROM);
			// setFromDialog(ExpertApplyForActivity.this);
			Utils.showPrgress(ExpertApplyForActivity.this);
			areaDialog.Getareathread();
			break;

		case R.id.ExpertApply_btn:
			if (StringUtil.isNullOrEmpty(UpData.getText().toString())) {
				Utils.showMessage(ExpertApplyForActivity.this, getResources()
						.getString(R.string.l_xb71));
			} else {
				Utils.showPrgress(ExpertApplyForActivity.this);
				Thread t = new Thread(new ApplyMaster());
				t.start();
			}

			break;
		case R.id.RL_UpData:

			// upData();
			showFileChooser();

			// ApplyMaster
			// Intent intent6=new
			// Intent(ExpertApplyForActivity.this,ModifyTheDataActivity.class);
			// intent6.putExtra("id", 6);
			// intent6.putExtra("KEY6", ""+UpData.getText().toString().trim());
			// startActivityForResult(intent6, UPDATA);
			break;
		}
	}

	// 选择sdcard的文件
	private void showFileChooser() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("*/*");
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		try {
			startActivityForResult(
					Intent.createChooser(intent,
							getResources().getString(R.string.l_xb72)),
					FILE_SELECT_CODE);
		} catch (android.content.ActivityNotFoundException ex) {
			// Potentially direct the user to the Market with a Dialog
			Toast.makeText(ExpertApplyForActivity.this,
					getResources().getString(R.string.l_xb73),
					Toast.LENGTH_SHORT).show();
		}
	}

	private void setSex() {
		// TODO Auto-generated method stub

		setSexDialog(ExpertApplyForActivity.this);
		setOnMyDialogeClistener(new OnMyDialogeClistener() {

			@Override
			public void Ok() {
				// TODO Auto-generated method stub
				// TextView t = (TextView) findViewById(TextOrimg_Id[9]);
				// t.setText("" + getSex());
//				   
				if (getSex().equals(getResources().getString(R.string.l_x4))) {
					userInfoModel.setSex("1");
				} else if (getSex().equals(
						getResources().getString(R.string.l_x3))) {
					userInfoModel.setSex("2");
				} else {
					userInfoModel.setSex("0");
				}
				userDataSet.UserDataSet(userInfoModel, 0, "", false);
				Intent intent = new Intent(ExpertApplyForActivity.this,
						ExpertApplyForActivity.class);
				intent.putExtra("userInfoModel", userInfoModel);
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.slide_left, R.anim.slide_right);

				// Thread t=new Thread(new RefreshDataThread(id));
				// t.start();

			}

			@Override
			public void Cancle() {
				// TODO Auto-generated method stub

			}
		});

	}

	// public void UpImgFile(final String path) {
	// Constants.UpImg_handler = handler;
	// // Utils.showPrgress(ExpertApplyForActivity.this);
	// UpdateImageThead imageThead = new UpdateImageThead(path,
	// ExpertApplyForActivity.this, true);
	// imageThead.start();
	// }

	/**
	 * 提交 (暂时还要改)
	 * 
	 * @author Administrator
	 * 
	 */
	public class ApplyMaster implements Runnable {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("uid", id);
			map.put("typeId", ExpertType);
			map.put("nickName", userInfoModel.getNickName());
			map.put("email", userInfoModel.getEmail());
			map.put("sex", userInfoModel.getSex());
			map.put("phone", userInfoModel.getPhone());
			map.put("areId", userInfoModel.getArea_id());
			map.put("dataInfo", fileUri);
			String content = Utils.sendRequest(map, Constants.BadiUrl
					+ "ApplyMaster");
			if (content != null) {
				Results results = Utils.checkResult_NNN(
						getApplicationContext(), content);
//				   ("达人申请的结果是:" + content + " "
//						+ results.getRetmsg());
				if (results != null && results.getRetmsg() != null) {
					//    
					try {
						if (results.isRet() == true) {
							handler.sendEmptyMessage(14);
						} else {
							handler.sendEmptyMessage(5);
						}
					} catch (Exception e) {
						   
					}
				}
			} else {
				Utils.ExitPrgress(ExpertApplyForActivity.this);
				handler.sendEmptyMessage(2);
			}
		}
	}

	public class RefreshDataThread implements Runnable {

		String id;

		public RefreshDataThread(String id) {
			this.id = id;

		}

		@Override
		public void run() {
			// TODO Auto-generated method stub

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", id);

			map.put("languageType", com.badibadi.mytools.Dialog
					.getSystemLanguageType(ExpertApplyForActivity.this));
			String content = Utils.sendRequest(map, Constants.BadiUrl
					+ "userDataShow");
			if (content != null) {
				//    ("结果是:" + content);
				Results results = Utils.checkResult_NNN(
						getApplicationContext(), content);
				if (results != null && results.getRetmsg() != null) {
//					   
					try {
						userInfoModel = JSONUtils.getEntityByJsonString(
								results.getRetmsg(), UserInfoModel.class);
						userInfoModel.setUid(id);
						handler.sendEmptyMessage(11);

					} catch (JSONException e) {
//						   ("解析出错");
						   
					} catch (Exception e) {
						// TODO Auto-generated catch block
//						   
						   
					}
				}
			} else {
				Utils.ExitPrgress(ExpertApplyForActivity.this);
				handler.sendEmptyMessage(2);

			}
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		getReturnData(requestCode, data);
		// 从sdcard中获取文件
		if (requestCode == FILE_SELECT_CODE && resultCode == Activity.RESULT_OK) {
			Uri uri = data.getData();
			String sdCardpath = IOUtils.UriToPath(ExpertApplyForActivity.this,
					uri);
//			   
			if (sdCardpath != null) {
				if (sdCardpath.endsWith(".JPG") || sdCardpath.endsWith(".jpg")
						|| sdCardpath.endsWith(".doc")
						|| sdCardpath.endsWith(".docx")
						|| sdCardpath.endsWith(".jpeg")
						|| sdCardpath.endsWith(".JPEG")) {
					
					
					String fileName=sdCardpath.substring(sdCardpath.lastIndexOf("/") + 1);
					XUtils.UpData(Utils.getUid(ExpertApplyForActivity.this), sdCardpath, fileName, ExpertApplyForActivity.this, handler, 15, 16);

					upData(sdCardpath);
				} else {
					Utils.showMessage(ExpertApplyForActivity.this,
							getResources().getString(R.string.wx_txt_120));
				}
			} else {
				Utils.showMessage(ExpertApplyForActivity.this, getResources()
						.getString(R.string.wx_txt_121));
			}

		}
	}

	/**
	 * 获取返回的数据
	 * 
	 * @param rcode
	 * @param data
	 */
	private void getReturnData(int rcode, Intent data) {
		// TODO Auto-generated method stub

		switch (rcode) {
		case MINGCHENG:
			if (data != null) {
				userInfoModel = (UserInfoModel) data
						.getSerializableExtra("ModifyTheDataActivity");
				if (userInfoModel != null) {
					if (userDataSet != null) {
						userDataSet.UserDataSet(userInfoModel, 0, "", false);
						Refresh();

					}

				}

			}
			break;
		case EMAIL:
			if (data != null) {
				userInfoModel = (UserInfoModel) data
						.getSerializableExtra("ModifyTheDataActivity");
				if (userInfoModel != null) {
					if (userDataSet != null) {
						userDataSet.UserDataSet(userInfoModel, 0, "", false);
						Refresh();
					}
				}

			}
			break;

		case PHONEUMBER:
			if (data != null) {
				userInfoModel = (UserInfoModel) data
						.getSerializableExtra("ModifyTheDataActivity");
				if (userInfoModel != null) {
					if (userDataSet != null) {
						userDataSet.UserDataSet(userInfoModel, 0, "", false);
						Refresh();
					}

				}

			}
			break;

		}

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		Utils.ExitPrgress(ExpertApplyForActivity.this);
		super.onDestroy();
	}
}
